package dao;

import java.util.List;

import model.Pessoa;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

public abstract class Daogeneric<T>  {
	
	private Class<T> clazz;
	

 	public T add(T obj) {
		Session session = Conexao.getSessionFactory().openSession();
		Transaction transaction = session.beginTransaction();
		try {
			session.save(obj);
			transaction.commit();
			session.refresh(obj);
			return obj;
		} catch (Exception e) {
			transaction.rollback();
			// TODO: handle exception
		} finally {
			session.close();
		}
		return null;
	}

	public T update(T obj) {
		Session session = Conexao.getSessionFactory().openSession();
		Transaction transaction = session.beginTransaction();
		try {
			session.update(obj);
			transaction.commit();
			session.refresh(obj);
			return obj;
		} catch (Exception e) {
			transaction.rollback();
			// TODO: handle exception
		} finally {
			session.close();
		}
		return null;
	}

	public T delet(T obj) {
		Session session = Conexao.getSessionFactory().openSession();
		Transaction transaction = session.beginTransaction();
		try {
			session.delete(obj);
			transaction.commit();
			return obj;
		} catch (Exception e) {
			transaction.rollback();
			// TODO: handle exception
		} finally {
			session.close();
		}
		return null;
	}

	//public Criteria getCriteria() {
		//Session session = Conexao.getSessionFactory().openSession();
		//Criteria criteria = session.createCriteria(clazz);
		//return criteria;
	//}
	
	public List<T> listar()   
    {  
		Session session = Conexao.getSessionFactory().openSession();
		Transaction transaction = session.beginTransaction();
        List<T> objts;  
        objts = null;  
         
        try {
        	Criteria selectAll = session.createCriteria(clazz);
        	//Criteria selectAll = getCriteria();
        	transaction.commit();  
            objts = selectAll.list();    
            return objts; 
		} catch (Exception e) {
			transaction.rollback();
		} finally {
			session.close();
		}
		return null;
    } 

	public T get(String nomeDoCampo, Object valor) {  
		Session session = Conexao.getSessionFactory().openSession();  
		return (T) session.createCriteria(Pessoa.class).add(Restrictions.eq(nomeDoCampo, valor)).uniqueResult();  
	}
}
